package main

import (
	"fmt"
	"log"
	"net/http"
	"strings"
	"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

// 定义全局的客户端map，用来存储所有连接的客户端
var clients = make(map[string]*websocket.Conn)

func handleConnections(w http.ResponseWriter, r *http.Request) {
	// 升级GET请求为WebSocket协议
	ws, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer ws.Close()

	username := r.URL.Query().Get("username")
	if username == "" {
		err := ws.WriteMessage(websocket.TextMessage, []byte("error,未传入username"))
		if err != nil {
			log.Println(err)
		}
		log.Println("error,未传入username")
		return
	}

	// 初始化一个新的客户端
	clients[username] = ws

	for {
		// 读取消息
		_, msg, err := ws.ReadMessage()
		if err != nil {
			log.Println(err)
			delete(clients, username)
			break
		}

		Message := string(msg)
		commandEndIndex := strings.Index(Message, ",")
		command := Message[0:commandEndIndex]
		targetUsernameToIndex := strings.Index(Message[commandEndIndex+1:], ",")
		targetUsername := Message[commandEndIndex+1 : commandEndIndex+1+targetUsernameToIndex]
		Message2 := Message[commandEndIndex+1+targetUsernameToIndex+1:]
		for c := range clients {
			if username == targetUsername {
				sendMessage := command + "," + Message2
				err := clients[username].WriteMessage(websocket.TextMessage, []byte(sendMessage))
				if err != nil {
					log.Println(err)
					clients[username].Close()
					delete(clients, c)
				}
			}
		}
	}
}

func main() {
	// 设置路由
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		handleConnections(w, r)
	})

	// 启动服务器
	fmt.Println("WebSocket 服务器启动，监听端口 8080...")
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
